package com.wfh.rpc.server;

import com.wfh.rpc.RpcApplication;
import com.wfh.rpc.model.RpcRequest;
import com.wfh.rpc.model.RpcResponse;
import com.wfh.rpc.registry.LocalRegistry;
import com.wfh.rpc.serializer.JdkSerializer;
import com.wfh.rpc.serializer.Serializer;
import com.wfh.rpc.serializer.SerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Title: HttpServerHandler
 * @Author wangfenghuan
 * @Package com.wfh.rpc.server
 * @Date 2025/10/12 12:39
 * @description: 请求处理器
 */
@Slf4j
public class HttpServerHandler implements Handler<HttpServerRequest> {
    @Override
    public void handle(HttpServerRequest httpServerRequest) {
        // 指定序列化器
        // 指定序列化器
        final Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

        // 记录日志
        log.info("Recevied request: {}, uri: {}", httpServerRequest.method(), httpServerRequest.uri());

        // 异步处理http请求
        httpServerRequest.bodyHandler(body -> {
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            try {
                rpcRequest = serializer.deserialize(bytes, RpcRequest.class);
            }catch (Exception e){
                e.printStackTrace();
            }
            // 构造响应结果对象
            RpcResponse rpcResponse = new RpcResponse();
            // 如果请求为null，就直接返回
            if (rpcRequest == null){
                rpcResponse.setMessage("request is null");
                doResponse(httpServerRequest, rpcResponse, serializer);
                return;
            }
            try{
                // 获取要调用的服务实现类，通过反射调用
                Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
                Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object result = method.invoke(implClass.newInstance(), rpcRequest.getArgs());
                // 封装返回结果
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            }catch (Exception e){
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }
            // 响应
            doResponse(httpServerRequest, rpcResponse, serializer);
        });

    }

    /**
     * 响应
     * @param httpServerRequest
     * @param rpcResponse
     * @param serializer
     */
    private void doResponse(HttpServerRequest httpServerRequest, RpcResponse rpcResponse, Serializer serializer) {
        HttpServerResponse response = httpServerRequest.response()
                .putHeader("content-type", "application/json");
        try{
            // 序列化
            byte[] serialize = serializer.serialize(rpcResponse);
            response.end(Buffer.buffer(serialize));
        }catch (IOException e){
            e.printStackTrace();
            response.end(Buffer.buffer());
        }
    }
}
